#define _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    struct Compare
    {
        bool operator()(const pair<int, string>& p1, const pair<int, string>& p2)
        {
            return (p1.first > p2.first) || (p1.first == p2.first && p1.second < p2.second);
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> CountMap;
        for (auto& str : words)
        {
            CountMap[str]++;
        }
        vector<pair<int, string>> v;

        for (auto& kv : CountMap)
        {
            v.push_back(make_pair(kv.second, kv.first));
        }
        stable_sort(v.begin(), v.end(), Compare());
        vector<string> vs;
        for (int i = 0; i < k; i++)
        {
            vs.push_back(v[i].second);
        }
        return vs;
    }
};